package com.lanou3g.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou3g.bean.Admin;
import com.lanou3g.bean.Menu;
import com.lanou3g.mapper.AdminMapper;
import com.lanou3g.service.AdminService;
import com.lanou3g.util.Result;

@Service
public class AdminServiceImpl implements AdminService {

	@Autowired
	private AdminMapper adminMapper;
	@Override
	public Admin findAdminByUsernameAndPassword(String username, String password) {
		return adminMapper.findAdminByUsernameAndPassword(username, password);
	}
	@Override
	public List<Menu> getMenusByRoleId(Integer roleId) {
		//获取该用户所具有的全部菜单信息
		List<Menu> menus = adminMapper.getMenusByRoleId(roleId);
		//对菜单进行分组
		List<Menu> groupedMenus = new ArrayList<>();
		for(int i = 0; i < menus.size();i ++) {
			Menu m = menus.get(i);
			Integer id = m.getId();
			Integer parentId = m.getParentId();
			if(parentId == 0) {
				//如果没有父id,说明自己是独立的,不能展开的.
				groupedMenus.add(m);
			}else {
				//如果有父id,说明自己需要加入到别的目录下面
				for(int j = 0; j < groupedMenus.size();j++) {
					Menu groupMenu = groupedMenus.get(j);
					if(parentId == groupMenu.getId()) {
						List<Menu> children = groupMenu.getChildren();
						if(children == null) {
							children = new ArrayList<Menu>();
							groupMenu.setChildren(children);
						}
						children.add(m);
					}
				}
			}
		}
		return groupedMenus;
	}
	@Override
	public int updateAdmin(Admin admin) {
		return adminMapper.updateAdmin(admin);
	}
	@Override
	public Admin findAdminById(Integer id) {
		return adminMapper.findAdminById(id);
	}

	@Override
	public Result getAdminsByPage(Integer page, Integer limit) {
		List<Admin> admins = adminMapper.getAllAdmins();
		PageHelper.startPage(page, limit);
		PageInfo<Admin> pageInfo = new PageInfo<>(admins);
		Result result = new Result();
		result.setCode(0);
		result.setMsg("获取成功");
		result.setCount(pageInfo.getTotal());
		result.setData(pageInfo.getList());
		return result;
	}
	@Override
	public Admin getAdminByUsername(String username) {
		return adminMapper.getAdminByUsername(username);
	}
	@Override
	public int insertAdmin(Admin admin) {
		return adminMapper.insertAdmin(admin);
	}
	@Override
	public int delAdminById(Integer id) {
		return adminMapper.delAdminById(id);
	}
	@Override
	public List<Admin> getFixAdmins() {
		return adminMapper.getFixAdmins();
	}

}
